package com.gingko.duominuo.ui.widget

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.TextView
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.gingko.duominuo.R
import com.gingko.duominuo.utils.dp2px
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import org.w3c.dom.Text


object LoadDialog : DialogFragment() {
    private var message: String? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        dialog?.run {
            window?.setBackgroundDrawableResource(android.R.color.transparent)
            window?.requestFeature(Window.FEATURE_NO_TITLE);
            setCanceledOnTouchOutside(false);
            setCancelable(false)
        }
        isCancelable = false
        val rootView = inflater.inflate(R.layout.dialog_progress, container, false);
        val tvMessage = rootView.findViewById<TextView>(R.id.tv_message)
        message?.let {
            tvMessage?.visibility = View.VISIBLE
            tvMessage?.text = message
        } ?: run { tvMessage?.visibility = View.GONE }
        return rootView
    }

    override fun onStart() {
        super.onStart()
        dialog?.window?.let {
            it.attributes.dimAmount = 0.0f
        }
    }

    override fun onResume() {
        super.onResume()
        dialog?.window?.run {
            setLayout(dp2px(110), dp2px(110))
            setBackgroundDrawable(ColorDrawable(Color.parseColor("#00000000")))
        }
    }

    fun show(manager: FragmentManager, tag: String?, message: String?) {
        try {
            this.message = message
            if (!isAdded && null == manager.findFragmentByTag(tag)) {
                manager.beginTransaction().remove(this).commitAllowingStateLoss()
                manager.beginTransaction().add(this, tag).commitAllowingStateLoss()
            } else {
                manager.beginTransaction().show(this).commitAllowingStateLoss()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    override fun dismiss() {
        runBlocking {
            try {
                delay(200)
                super.dismissAllowingStateLoss()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

}